﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace socketAssist.Procol
{
    public class MyProcolDecoder : LengthFieldBasedFrameDecoder
    {
        public MyProcolDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) : 
            base(ByteOrder.LittleEndian,maxFrameLength, 0, 4,3,0,true)
        {
        }
        public MyProcolDecoder()    
            :this(int.MaxValue,0,4)
        {

        }
        protected override object Decode(IChannelHandlerContext context, IByteBuffer input)
        {
            input=(IByteBuffer)base.Decode(context, input);
            if (input == null)
            {
                return null;
            }
            //input=(IByteBuffer) base.Decode(context, input);
            var totalLen = input.ReadableBytes;
            if (totalLen < 7)
            {
                throw new Exception("长度不对");
            }
            var bodySize = input.ReadIntLE();
            var cmd = input.ReadShortLE();
            var crc = input.ReadByte();
            if (bodySize != totalLen - 7)
            {
                throw new Exception("Body长度不对");
            }
            var body = input.ReadString((int)bodySize-1,Encoding.UTF8);

            return body;
        }
    }
}
